package com.hqq.exercise.list;

/**
 * ReverseList 反转列表
 * 题目描述:
 * 定义一个函数，输入一个链表的头结点，反转该链表并输出反转后链表的头结点。
 * Created by heqianqian on 2017/8/11.
 */
public class ReverseList {

    /**
     * 递归实现链表反转 从尾部开始处理
     */
    public static ListNode reverseListByRecursion(ListNode head) {
        ListNode prev = null;
        if (head == null || head.next == null) {
            return head;
        } else {
            ListNode temp = reverseListByRecursion(head.next);
            head.next.next = head;
            head.next = null;
            prev = temp;
        }
        return prev;
    }

    /**
     * 循环实现链表反转 从头部开始处理
     */
    public static ListNode reverseListByLoop(ListNode head) {
        ListNode prev = null;
        while (head != null) {
            ListNode temp = head;//B
            head = head.next;//head = B
            temp.next = prev;
            prev = temp;
        }
        return prev;
    }
}
